package Windows.DownLoads;

import java.awt.GridLayout;
import java.io.File;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JScrollPane;

import DBUtil.CNN;
import GroupWare.DownloadTask;
import GroupWare.Pip;
import GroupWare.ShareRoot;
import Tools.IMG;
import Tools.Log;
import Windows.MainWindows;
import Windows.PicPanel;
import Windows.Tree.ResTree;
import Windows.Tree.TreeNodePic;
import XML.XML;
import XML.XMLNode;

public class ShowDownloadPanel extends JScrollPane {
	private static final int HEIGHT = 80;
	public ArrayList<ShowDownloadTaskPanel> alsdf = new ArrayList<ShowDownloadTaskPanel>();
	public GridLayout gbl = new GridLayout(1, 1, 2, 2);
	public final PicPanel mp = new PicPanel(IMG.DownBg);
	Date readyTime;
	private ShareRoot sp;
	private int k = -1;// 游标
	TreeNodePic treeNode = new TreeNodePic("正在下载", IMG.DownNode);
	ResTree Tree;

	public ShowDownloadPanel(ResTree Tree, ShareRoot sp) {
		super();
		this.sp = sp;
		this.Tree = Tree;
		mp.setLayout(gbl);
		readyTime = new Date();
		PicPanel mypanel = new PicPanel(IMG.DownBG);
		setViewportView(mypanel);
		// mypanel.setLayout();
		mypanel.add(mp);
		// mp.setBounds(0, 0, getSize().width,(aldf.size())*HEIGHT );
		// mp.setSize(this.getSize().width, aldf.size()/2*150);
		// downFile df = new downFile("test.txt",100000,105090009,new
		// sharePath(new File("")));
		// this.add(new ShowDownloadFile(df));
		// this.add(new ShowDownloadFile(df));
		// this.add(new ShowDownloadFile(df));
		// this.add(new ShowDownloadFile(df));
		// this.setVisible(true);
		readTask(CNN.taskDir);
	}

	public void addFile(XMLNode xf) {
		// String filepath = xf.get("FilePath");
		// long size = Long.parseLong(xf.get("size"));
		// long LastModified = Long.valueOf(xf.get("time"));

		DownloadTask df = new DownloadTask(xf, MainWindows.getInstance().client.sp);

		ShowDownloadTaskPanel sdf = newTask(df);
		addtask(sdf);

		Log.print("[新建任务]" + xf);

		// address="/127.0.0.1" sport="3616"
		Pip p;
		try {
			String userid = xf.get("userid");
			String ip = xf.get("address");
			p = new Pip(0, 0, userid, InetAddress.getByName(ip.substring(1, ip.length())), Integer.parseInt(xf.get("sport")));
			sdf.getDf().addSeed(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
		sdf.getDf().start();// 启动任务

		// 滑出创建任务信息窗口
		if (df.getXML().FLAG.length() != 16) {
			df.getXML().put("State", "new");
			new ShowDownloadWindow(df).start();
		}

		// this.add
		// alxf.add(xf);
		// // --取资源文件全名
		// String name = df.f.getName();
		// int j = name.lastIndexOf('.');
		// // --取资源类型名
		// String type = j != -1 ? name.substring(j, name.length()) : "未知";
		// // --取资源名称
		// name = j != -1 ? name.substring(0, j) : name;
		// // --格式化文件更新日期
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// long time = df.getLastModified();
		// // 插入一行记录
		// Object[] obj = {"安全",name,type,
		// "(256)",df.getSizeStr(),df.achieveStr,
		// df.dAchieve,df.speedStr,df.resStr,sdf.format(new Date(time)),df.md5};
		// mt.addRow(obj);//添加一行
		// table.updateUI();//发出的表明 L&F 已经更改的通知。用 UIManager 的最新版本替换当前的 UI 对象。
	}

	public void addtask(ShowDownloadTaskPanel sdf) {
//		Log.print("[添加任务]" + sdf);
		MainWindows.getInstance().client.addClientListenser(sdf);// 注册客户端数据监听器

		if (alsdf.indexOf(sdf) != -1) {
			return;
		}
		sdf.setSdp(this);

		treeNode.add(sdf.treeNode);
		mp.add(sdf);
		alsdf.add(sdf);
		gbl.setRows(alsdf.size());// 更新行数

		mp.updateUI();
		Tree.updateUI();
	}

	public ArrayList<ShowDownloadTaskPanel> getAldf() {
		return alsdf;
	}

	public int getK() {
		return k;
	}

	public DownloadTask getSelectDF() {
		if (k < 0)
			return null;
		return alsdf.get(k).getDf();
	}

	public TreeNodePic getTreeNode() {
		return treeNode;
	}

	/**
	 * 查找下载任务的集合索引
	 * 
	 * @param md5
	 *            文件md5
	 * @return 索引 -1表示未找到
	 */
	public int indexOfdf(String md5) {
		for (int i = 0; i < alsdf.size(); i++) {
			if (alsdf.get(i).getMd5().equals(md5))
				return i;
		}
		return -1;
	}

	/**
	 * 生产一个任务
	 * 
	 * @param df
	 * @return
	 */
	public ShowDownloadTaskPanel newTask(DownloadTask df) {
		return new ShowDownloadTaskPanel(df);
	}

	/**
	 * 读取指定目录下的配置文件
	 * 
	 * @param path
	 *            任务记录目录
	 */
	public void readTask(File path) {

		File[] f = path.listFiles();
		for (int i = 0; i < f.length; i++) {
//			Log.print(f[i].getAbsolutePath());
			if (f[i].isFile() && f[i].getName().endsWith(".xml")) {
				String md5 = f[i].getName().substring(0, f[i].getName().length() - 4);
				XML xml = new XML(f[i]);
				XMLNode xf = (XMLNode) xml.GetPathValue(md5);
				if (xf != null) {
					xml.copy(xf);
					addtask(newTask(new DownloadTask(xml, sp)));
				}
			}
		}
	}

	public void removeTask(ShowDownloadTaskPanel sdf) {
//		Log.print("[移除任务]" + sdf);
		MainWindows.getInstance().client.removeClientListenser(sdf);// 注销监听客户端指令监听

		treeNode.remove(sdf.treeNode);
		mp.remove(sdf);
		alsdf.remove(sdf);
		gbl.setRows(alsdf.size());
		sdf.df.pause();

		sdf.df.getXmlFile().delete();
		try {
			sdf.df.raf.close();
		} catch (Exception e) {
		}
		if (sdf.df.getAchieve() < sdf.df.length) {
			sdf.df.getF().delete();
		}
		mp.updateUI();
		MainWindows.Tree.jTree.updateUI();
	}

	public void setAldf(ArrayList<ShowDownloadTaskPanel> aldf) {
		this.alsdf = aldf;
	}

	public void setK(int k) {
		this.k = k;
	}

}
